<?php

class PersonalCenterController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		);
	}

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('addaddress','getaddresslist','deladdress','setdefaultaddress','updateaddress','getgradeLog','getattentions','cancelattentions'),
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    public function actionAddCowry($gid) {
        //TODO 根据商品获得订单ID
    }

    public function actionGetGowrys($type=0,$uploadtime=-1) {

    }

    public function actionGetCommons($createtime=-1) {

    }

    public function actionAddCommons() {

    }

    /**
     * 添加地址信息
     */
    public function actionAddAddress() {

        $address = new UserAddress();
        if (isset($_POST["address"])) {
            $address->address = $_POST["address"];
        }
        if (isset($_POST["consignee"])) {
            $address->consignee = $_POST["consignee"];
        };
        if (isset($_POST["mobile"])) {
            $address->mobile = $_POST["mobile"];
        };

        if (isset($_POST["telephone"])) {
            $address->telephone = $_POST["telephone"];
        };
        if (isset($_POST["email"])) {
            $address->email = $_POST["email"];
        };
        $address->userid = CommonUtils::getUserId();
        $address->save();

        $user = UserInfo::model()->findByPk(new MongoId($address->userid));
        if(empty($ser->defaultAddress))
        {
            $user->defaultAddress = (string)$address->_id;
            $user->save(false);
        }
        echoToMobile("ok");
    }

    /**
     * 得到地址列表
     */
    public function actionGetAddressList() {
        $query = array(
            'conditions' => array('userid'=>array('=='=>CommonUtils::getUserId())),
        );

        $userInfo = UserInfo::model()->findByPk(new MongoId(CommonUtils::getUserId()));

        $result = UserAddress::model()->findAll($query);
        $defaultAddress = null;
        foreach ($result as $key => $value) {
            if((string)$value->_id == $userInfo->defaultAddress)
            {
                $defaultAddress = $value;
                unset($result[$key]);
                break;
            }
        }
        if(!empty($defaultAddress))
            array_unshift($result,$defaultAddress);

        echoToMobile($this->editids($result));
    }

    /**
     * 删除地址
     * @param $addressid
     */
    public function actionDelAddress($addressid) {
        $address = $this->getAddress($addressid);
        if ($address->userid==CommonUtils::getUserId()) {
            $address->delete();
            $user = UserInfo::model()->findByPk(new MongoId($address->userid));
            if(!empty($user) && $user->defaultAddress == (string)$address->_id){
                $user->defaultAddress = null;
                $user->save(false);
            }
            echoToMobile("ok");
        } else {
            echoToError(_ERROR_SYSTEM_FAULT);
        }
    }

    /**
     * 设置缺省地址
     * @param $addressid
     */
    public function actionSetDefaultAddress($addressid) {
        $user =UserInfo::model()->findByPk(new MongoId((CommonUtils::getUserId())));
        $user->defaultAddress = $addressid;
        $user->update();
        echoToMobile("ok");
    }

    /**
     * 更新地址信息
     * @param $addressid
     */
    public function actionUpdateAddress($addressid) {
        $address = new UserAddress();
        $address->_id = new MongoId($addressid);
        if (isset($_POST["address"])) {
            $address->address = $_POST["address"];
        }
        if (isset($_POST["consignee"])) {
            $address->consignee = $_POST["consignee"];
        };
        if (isset($_POST["mobile"])) {
            $address->mobile = $_POST["mobile"];
        };
        if (isset($_POST["telephone"])) {
            $address->telephone = $_POST["telephone"];
        };
        if (isset($_POST["email"])) {
            $address->email = $_POST["email"];
        };
        $address->userid = CommonUtils::getUserId();
        $address->setIsNewRecord(false);
        $address->update();
        echoToMobile("ok");
    }

    /**
     * 获得积分日志
     *
     * @param $time
     */
    public function actionGetGradeLog($time=0) {
        $userid = CommonUtils::getUserId();
        if ($time!=0) {
            $query = array(
                'conditions' => array('createtime'=>array('<'=>$time),'userid'=>array('=='=>$userid)),
                'limit'=>_LIMITED_PAGE_SIZE,
                'sort'=> array('createtime'=>EMongoCriteria::SORT_DESC)
            );
        } else {
            $query = array(
                'conditions' => array('userid'=>array('=='=>$userid)),
                'limit'=>_LIMITED_PAGE_SIZE,
                'sort'=> array('createtime'=>EMongoCriteria::SORT_DESC)
            );
        }

        $result = UserGradeLog::model()->findAll($query);
        echoToMobile($result);
    }

    /**
     * 得到我的关注
     *
     */
    public function actionGetAttentions($start=0) {
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $desc_field ='desc_zn';
            $name_field = 'name_zn';
        } else {
            $desc_field ='desc_en';
            $name_field = 'name_en';
        }

        $resultArr = array();

        $userid = CommonUtils::getUserId();
        $query = array(
            'limit'=>_LIMITED_PAGE_SIZE,
            'sort'=> array('createtime'=>EMongoCriteria::SORT_DESC),
            'offset'=>(int)$start,
            'conditions'=>array('userid'=>array('=='=>$userid)),
        );
        // if ($time>0) {
        //     $query['conditions'] = array('userid'=>array('=='=>$userid));
        // } else {
        //     $query['conditions'] = array('userid'=>array('=='=>$userid));
        // }
        $attentions = UserAttention::model()->findAll($query);
        if (!empty($attentions) && count($attentions)>0) {
            $len = count($attentions);
            for($index=0;$index<$len;$index++) {
                $item = array();
                $goodsid =$attentions[$index]->goods;
                $goods = $this->getGoodsBaseInfo($goodsid);
                $item['aid'] = (string)$attentions[$index]->_id;
                $item['name'] = $goods->$name_field;
                // $item['desc'] = $goods->$desc_field;
                $item['originPrice'] = $goods->originPrice;
                $item['price'] = $price = RedisCacheUtil::getPrice($goodsid)?$price:$goods->originPrice;
                $item['icon']= $goods->icon;
                $item['hots'] = RedisCacheUtil::getGoodsHot($goodsid);
                $item['goods'] = $goodsid;
                array_push($resultArr,$item);
            }
        }
        echoToMobile($resultArr);
    }

    /**
     * 取消关注
     * @param $aid
     */
    public function actionCancelAttentions($aid) {
        $userid = CommonUtils::getUserId();
        $userAttention =  UserAttention::model()->findByPk(new MongoId($aid));
        if ($userAttention->userid==$userid) {
            UserAttention::model()->deleteByPk(new MongoId($aid));
            $goodsTotalInfo = GoodsTotalInfo::model()->find(array('conditions'=>array('goods'=>array('=='=>$userAttention->goods))));
            $goodsTotalInfo->favoritesNum = $goodsTotalInfo->favoritesNum-1;
            $goodsTotalInfo->update();
            RedisCacheUtil::cancelFavorites($userAttention->goods);
            $this->updateHots($userAttention->goods,RedisCacheUtil::getGoodsHot($userAttention->goods));
            echoToMobile("ok");
        } else {
            echoToError(_ERROR_SYSTEM_NO_ALLOW);
        }
    }


    /**ßßßß
     * 获得用户信息
     * @param $userid
     * @return EMongoDocument
     */
    function getUser($userid) {
        $mongoid = new MongoId($userid);
        $query = array(
            'conditions' => array('_id'=>array('=='=>$mongoid)),
        );
        return UserInfo::model()->find($query);
    }

    /**
     * 得到地址信息
     */
    private function getAddress($addressId) {
        $query = array(
            'conditions' => array('_id'=>array('=='=>new MongoId($addressId))),
        );
        return UserAddress::model()->find($query);
    }

    private function editids($data) {
        $result = array();
        if (!empty($data)) {
            $len = count($data);
            for($index=0;$index<$len;$index++) {
                $item = array();
                foreach($data[$index] as $key => $value) {
                    if($key=='_id') {
                        $item['id'] = (string)$value;
                    } else {
                        $item[$key] = $value;
                    }
                }
                if (isset($item['userid'])) {

                    unset($item['userid']);
                }
                array_push($result,$item);
            }

        }
        return $result;
    }

    public function actionGetUserInfo() {
        $userid = CommonUtils::getUserId();
        $result = UserInfo::model()->findAllByPk(new MongoId($userid));
        echoToMobile($result);
    }


    /*
     *
     * 得到商品基础信息
     *
     * @param $id
     */
    private function getGoodsBaseInfo($gid) {
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $desc_field ='desc_zn';
            $name_field = 'name_zn';
        } else {
            $desc_field ='desc_en';
            $name_field = 'name_en';
        }

        $mongoid = new MongoId($gid);
        $query = array(
            'conditions' => array('_id'=>array('=='=>$mongoid)),
            'select'=>array($name_field,$desc_field,'freight','icon','images','originPrice','_id'),
        );
        return Goods::model()->find($query);
    }

    private function updateHots($id,$hots)
    {
        $this->updateIndex($id,'hots',$hots);
    }



    private function updateIndex($id,$key,$value)
    {
        $solrUtil = new SolrUtil(_SOLR_ADDRESS, _SOLR_GOODS_ZN);
        $solrUtil->update(array('id' => $id,$key=>array('set'=>$value)));

        $solrUtil = new SolrUtil(_SOLR_GOODS_EN, _SOLR_ADDRESS);
        $solrUtil->update(array('id' => $id,$key=>array('set'=>$value)));
    }



}